<template>
  <div class="seller-products">
    <h2>商品管理</h2>
    
    <!-- 商品列表 -->
    <el-card>
      <div class="header-actions">
        <el-button type="primary" @click="showAddDialog = true">
          <el-icon><Plus /></el-icon>
          发布商品
        </el-button>
      </div>
      
      <el-table :data="products" v-loading="loading">
        <el-table-column prop="name" label="商品名称" min-width="200" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">¥{{ scope.row.price }}</template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'ON_SALE'" type="success">在售</el-tag>
            <el-tag v-else-if="scope.row.status === 'OFF_SHELF'" type="info">下架</el-tag>
            <el-tag v-else-if="scope.row.status === 'PENDING'" type="warning">待审核</el-tag>
            <el-tag v-else-if="scope.row.status === 'REJECTED'" type="danger">被拒绝</el-tag>
            <el-tag v-else>{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="editProduct(scope.row)">编辑</el-button>
            <el-button
              v-if="scope.row.status === 'ON_SALE'"
              size="small"
              type="warning"
              @click="toggleStatus(scope.row)"
            >下架</el-button>
            <el-button size="small" type="danger" @click="deleteProduct(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingProduct ? '编辑商品' : '发布商品'"
      width="500px"
    >
      <el-form :model="productForm" :rules="productRules" ref="productFormRef" label-width="80px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        
        <el-form-item label="商品价格" prop="price">
          <el-input-number 
            v-model="productForm.price" 
            :precision="2" 
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="商品库存" prop="stock">
          <el-input-number 
            v-model="productForm.stock" 
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="商品图片" prop="mainImage">
          <el-input v-model="productForm.mainImage" placeholder="请输入图片URL" />
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="productForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="productForm.categoryId" placeholder="请选择商品分类">
            <el-option v-for="cat in categories" :key="cat.categoryId" :label="cat.name" :value="cat.categoryId" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveProduct" :loading="saving">
          {{ editingProduct ? '更新' : '发布' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const saving = ref(false)
const showAddDialog = ref(false)
const editingProduct = ref(null)
const products = ref([])
const categories = ref([])

const productForm = reactive({
  name: '',
  price: 0,
  stock: 0,
  mainImage: '',
  description: '',
  categoryId: null
})

const productRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  mainImage: [
    { required: true, message: '请输入商品图片URL', trigger: 'blur' }
  ]
}

const productFormRef = ref()

// 加载商品列表
const loadProducts = async () => {
  loading.value = true
  try {
    const response = await request.get('/api/seller/products')
    if (response.success) {
      products.value = response.data
    }
  } catch (error) {
    ElMessage.error('加载商品列表失败')
  } finally {
    loading.value = false
  }
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const res = await request.get('/api/categories')
    categories.value = Array.isArray(res) ? res : (res.data || [])
  } catch (e) {
    categories.value = []
  }
}

// 编辑商品
const editProduct = (product) => {
  editingProduct.value = product
  Object.assign(productForm, {
    name: product.name,
    price: product.price,
    stock: product.stock,
    mainImage: product.mainImage,
    description: product.description,
    categoryId: product.categoryId
  })
  showAddDialog.value = true
}

// 保存商品
const saveProduct = async () => {
  if (!productFormRef.value) return
  
  const valid = await productFormRef.value.validate()
  if (!valid) return

  saving.value = true
  try {
    if (editingProduct.value) {
      await request.put(`/api/seller/products/${editingProduct.value.productId}`, productForm)
      ElMessage.success('商品更新成功')
    } else {
      await request.post('/api/seller/products', productForm)
      ElMessage.success('商品发布成功')
    }
    
    showAddDialog.value = false
    resetProductForm()
    loadProducts()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    saving.value = false
  }
}

// 重置商品表单
const resetProductForm = () => {
  editingProduct.value = null
  Object.assign(productForm, {
    name: '',
    price: 0,
    stock: 0,
    mainImage: '',
    description: '',
    categoryId: null
  })
}

// 切换商品状态
const toggleStatus = async (product) => {
  try {
    const newStatus = product.status === 'ON_SALE' ? 'OFF_SHELF' : 'ON_SALE'
    await request.put(`/api/seller/products/${product.productId}/status`, { status: newStatus })
    ElMessage.success('状态更新成功')
    loadProducts()
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

// 删除商品
const deleteProduct = async (product) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await request.delete(`/api/seller/products/${product.productId}`)
    ElMessage.success('商品删除成功')
    loadProducts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  loadCategories()
  loadProducts()
})
</script>

<style scoped>
.seller-products {
  max-width: 1000px;
  margin: 0 auto;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.header-actions {
  margin-bottom: 20px;
}
</style> 